package com.zuorenke;

import com.zuorenke.vertx.DeployVertxServer;
import com.zuorenke.vertx.WebRouterInitializer;
import com.zuorenke.vertx.VertxUtil;
import com.zuorenke.vertx.config.VertxProperties;
import io.vertx.core.Vertx;
import io.vertx.core.VertxOptions;
import io.vertx.ext.web.Router;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.EnableScheduling;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author Z.R.K
 * @description
 * @create 2019-04-06 17:07:39
 **/
@SpringBootApplication
@EnableScheduling
@EnableCaching
@Slf4j
public class VertxApplication {
	@Resource
	private VertxProperties vertxProperties;
	
	public static void main(String[] args) {
		SpringApplication.run(VertxApplication.class, args);
	}
	
	private void setVertxEnv(VertxProperties vertxProperties){
		if(vertxProperties.getDisableHeaderCheck() == null) {
			vertxProperties.setDisableHeaderCheck("false");
		}
		if(vertxProperties.getDisableMetrics() == null) {
			vertxProperties.setDisableMetrics("false");
		}
		System.setProperty("vertx.disableHttpHeadersValidation", vertxProperties.getDisableHeaderCheck());
		System.setProperty("vertx.disableMetrics", vertxProperties.getDisableMetrics());
		System.setProperty("vertx.disableDnsResolver", vertxProperties.getDisableMetrics());
		
	}
	
	@EventListener
	public void deployVerticles(ApplicationReadyEvent event) {
		setVertxEnv(vertxProperties);
		Vertx vertx = Vertx.vertx(
				new VertxOptions().setWorkerPoolSize(vertxProperties.getWorkerPoolSize())
				.setMaxEventLoopExecuteTime(99999999L)
				.setBlockedThreadCheckInterval(10000000)
				.setMaxWorkerExecuteTime(1000000000L)
		);
		VertxUtil.init(vertx);
		try {
			Router router = new WebRouterInitializer(vertxProperties.getHandlerPackages()).initRouter();
			DeployVertxServer.startDeploy(router, vertxProperties);
		} catch (IOException e) {
			log.error("IOException {}", e);
		}
	}
}
